package cn.wolfcode.p2p.website.interceptor;

import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.util.RequireLogin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //handler分为两种情况
        //1.请求的是静态资源,handler是DefaultHandlerServlet
        //2.请求的是动态资源,此时handler参数对应的handlerMethod对象(封装马上要访问的控制器方法的引用)
        if (handler instanceof HandlerMethod) {
            //判断请求方法上是否贴有RequireLogin注解
            HandlerMethod method = (HandlerMethod) handler; //马上要访问到的方法的引用的包装对象
            RequireLogin rl = method.getMethodAnnotation(RequireLogin.class);
            if (rl != null){
                //如果有贴,说明该方法访问的时候需要先登录
                //判断用户是否登录
                if (UserContext.getCurrent() == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
            //如果有登录,放行请求

        }
        return true;
    }
}
